<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-circle-plus-outline"
                   plain
                   @click="handleAdd">发起调查问卷
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
                   <!-- v-if="permission.vote_delete" -->
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="stop">终止调查
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-refresh-right"
                   plain
                   @click="reStart">恢复调查
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-reading"
                   plain
                   @click="handleResult">调查结果
        </el-button>
      </template>


      <template slot-scope="scope" slot="menu">
        <el-button type="text" size="small" @click="voteInfo(scope.row)">投票</el-button>
      </template>

      <template slot="itemForm">
        <avue-crud  :option="infoOption" 
                    :data="infoData"
                    @row-update="itemRowUpdate"
                    @row-save="itemRowSave"
                    @row-del="itemRowDel">
        </avue-crud>
      </template>
    </avue-crud>
    <el-dialog title="培训课程投票项信息" append-to-body :visible.sync="dialogVisable" width="500px">
        <el-table
          height="300px"
          border
          :data="tableList"
        >
          <el-table-column type="index" width="50" label="序号" align="left"></el-table-column>
          <el-table-column
            prop="tpx"
            label="课程名称"
            width="250"
            header-align="center"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="voteNum"
            label="投票数"
            width="200"
            header-align="center"
            align="center"
          ></el-table-column>
        </el-table>
        <template slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            icon="el-icon-circle-close"
            @click="dialogVisable = false"
            >关闭</el-button
          >
        </template>
    </el-dialog>
    <el-dialog title="投票页面" append-to-body :visible.sync="voteDialogVisable" width="90%" top="5vh">
      <div class="voteInfoDiv" v-if="!isVote">
        <!-- <basic-container>
          <div style="height:80%;"> -->
            <e-chart 
              autoresize 
              :options="gradeChartOptions"
              style="height:60vh;">
            </e-chart>
          <!-- </div>
        </basic-container> -->
      </div>
      <div class="voteDiv" v-if="isVote">
        <h3>请选择您想培训的课程</h3>
        <el-divider></el-divider>
        <!-- <ul class="ulBox" v-for="item in voteInfoList">
            <li>坚持坚持坚持</li>
			      <li style="float:left">坚持坚持坚持</li>
          </ul>
          <ol>

          </ol> -->
        <el-checkbox-group v-model="voteCheckList" @change="voteCheckChanged" style="height:60vh;">
          <el-checkbox v-for="item in voteInfoList" :label="item.id" :key="item.id">{{item.tpx}}<div style="float: right;display: inline-block;">{{item.voteNum + "票"}}</div></el-checkbox>
        </el-checkbox-group>
      </div>
      <template slot="footer" class="dialog-footer">
          <el-button v-if="isVote"
            type="primary"
            icon="el-icon-data-line"
            @click="submitVote"
            >提交投票</el-button
          >
          <!-- <el-button v-if="isVote"
            type="primary"
            icon="el-icon-data-line"
            @click="showVoteTotal"
            >统计信息</el-button
          > -->
          <!-- <el-button v-if="!isVote"
            type="primary"
            icon="el-icon-document-checked"
            @click="showVote"
            >投票信息</el-button
          > -->
          <el-button
            type="primary"
            icon="el-icon-circle-close"
            @click="voteDialogVisable = false"
            >关闭</el-button
          >
        </template>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, add, remove, getVoteResult, updataStatusByIds} from "@/api/jypx/eduvote/vote";
  import {getVoteDetail} from "@/api/jypx/eduvoteitem/voteitem";
  import {addRecord} from "@/api/jypx/eduvoterecord/voterecord";
  import {mapGetters} from "vuex";
import done from '../../work/done.vue';

  export default {
  components: { done },
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          labelWidth: 130,
          tip: false,
          // showOverflowTooltip: true,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: false,
          addBtn: false,
          editBtn: false,
          delBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            // {
            //   label: "主键",
            //   prop: "id",
            //   rules: [{
            //     required: true,
            //     message: "请输入主键",
            //     trigger: "blur"
            //   }]
            // },
            {
              label: "培训调查主题",
              prop: "pxdczt",
              width: 140,
              rules: [{
                required: true,
                message: "请输入调查主题",
                trigger: "blur"
              }]
            },
            {
              label: "最高投票课程",
              prop: "mostlyVoteTPX",
              width: 150,
              display: false
            },
            {
              label: "限定投票数",
              prop: "xdtps",
              rules: [{
                required: true,
                message: "请输入限定投票数",
                trigger: "blur"
              },{
                pattern: /^(([1-9]{1}\d*)|(0{1}))?$/,
                message: "请输入数字",
                trigger: "blur"
              }]
            },
            {
              label: "是否投票",
              prop: "isVote",
              dicData: [
                {
                  label: "是",
                  value: 1
                },
                {
                  label: "否",
                  value: 0
                }
              ],
              display: false
            },
            {
              label: "培训调查是否结束",
              prop: "status",
              width: 140,
              dicData: [
                {
                  label: "是",
                  value: 1
                },
                {
                  label: "否",
                  value: 0
                }
              ],
              display: false
            },
            {
              labelWidth: 130,
              label: '培训课程投票项',
              prop: 'item',
              span: 24,
              hide: true,
              formslot: true,
            }
          ]
        },
        infoOption:{
          column: [{
            label: '课程名称',
            prop: 'tpx',
            rules: [{
                      required: true,
                      message: "请输入课程名称",
                      trigger: "blur"
                    }]
          },{
            label: '排序',
            prop: 'px',
            display: false
          }]
       },
        data: [],
        pxIndex: 0,
        dialogVisable: false,
        tableList: [],
        // ----------投票也相关--------
        voteDialogVisable: false,
        gradeChartOptions: {},
        labelValue: {
          normal: {
            show: true,
            position: "top"
          }
        },
        isVote: false,
        voteCheckList: [],
        voteInfoList: [],
        currentVoteId: null
      };
    },
    watch: {
      'form.voteItems':{
        handler(val) {
          const xdtpsDom = this.findObject(this.option.column,'xdtps');
          if (!val || val.length == 0) {
            xdtpsDom.disabled = true
          } else {
            xdtpsDom.disabled = false
          }
        }
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          // addBtn: this.vaildData(this.permission.vote_add, false),
          // viewBtn: this.vaildData(this.permission.vote_view, false),
          // delBtn: this.vaildData(this.permission.vote_delete, false),
          // editBtn: this.vaildData(this.permission.vote_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      infoData() {
        if (!this.form.voteItems) {
          this.form.voteItems = []
        }
        return this.form.voteItems
      }
    },
    methods: {
      voteCheckChanged(newVal) {

      },
      submitVote() {
        if (this.voteCheckList.length == 0) {
          this.$message.warning("请选择至少一项投票项！");
          return
        }
        const paramList = [];
        this.voteCheckList.forEach((item) => {
            paramList.push({
              voteId: this.currentVoteId,
              voteItemId: item
            });
        })
        addRecord(paramList).then(() => {
          this.voteDialogVisable = false
        });
      },
      showVoteTotal() {
        this.isVote = false;
      },
      showVote() {
        this.isVote = true;
      },
      initChartOptions(resData) {
        let xData = [];
        let yData = [];
        this.voteInfoList = resData.data.data
        resData.data.data.forEach(item => {
          const r = Math.round(Math.random()*255);
          const g = Math.round(Math.random()*255);
          const b = Math.round(Math.random()*255);
          const a = ( (Math.random()*5 + 5) / 10 ).toFixed(2)
          xData.push(item.tpx);
          yData.push({
              // name: "A",
              value: item.voteNum,
              label: this.labelValue,
              itemStyle: {
                // color: this.getRandomColor()
                color: `rgba(${r},${g},${b},${1})`
              }
          });
        });
        this.gradeChartOptions = {
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "line"
            }
          },
          grid: {
            left: "4%",
            right: 80,
            bottom: "4%",
            containLabel: true
          },
          xAxis: {
            name: "",
            data: xData,
            axisLabel: {
              color: "#888"
            },
            splitLine: {
              show: true
            }
          },
          yAxis: { 
            name: "",
            minInterval: 1
          },
          series: [{
            type: "bar",
            barWidth: "25%",
            data: yData
            // [
              // {
              // name: "A",
              // value: resData.gradeAyAxis[0],
              // label: this.labelValue,
              // itemStyle: {
              //   color: "#EA4242"
              // }
            // ]
          }],
        };
      },
      itemRowSave(row, done, loading) {
        row.px = this.pxIndex;
        this.form.voteItems.push(row);

        this.pxIndex++;
        done();
      },
      itemRowUpdate(row, index, done, loading) {
        this.form.voteItems.splice(index,row);
        done();
      },
      itemRowDel(row, index) {
        this.form.voteItems.splice(index);
      },
      voteInfo(row) {
        // this.$router.replace({name: "/#/jypx/eduvoterecord/voterecord", params: {voteId: row.id}})
        this.currentVoteId = row.id;
        this.isVote = row.isVote == 0 && row.status == 0;
        getVoteDetail(row.id).then(res => {
          this.voteDialogVisable = true;
          this.initChartOptions(res);
        });
        // testRecord(row)
      },
      handleResult(){
        if (this.selectionList.length !== 1) {
          this.$message.warning("请选择一条数据");
          return;
        }
        this.tableList = []
        getVoteResult(this.selectionList[0].id).then(res => {
          this.tableList = res.data.data;
        });
        this.dialogVisable = true
      },
      handleAdd() {
        this.$refs.crud.rowAdd()
        this.pxIndex = 0
        console.log("888888888888888888:", this.form)
      },
      rowSave(row, done, loading) {
        if (row.voteItems.length === 0) {
          this.$message({
            type: "warning",
            message: "请添加培训课程投票项!"
          });
          loading();
          return
        }
        if (row.voteItems.length < row.xdtps) {
          this.$message({
            type: "warning",
            message: "限定投票数不能大于投票项数量!"
          });
          loading();
          return
        }
        // console.log('test 参数：', row);
        // done();
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      stop() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将已选择调查终止?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
            return updataStatusByIds(this.ids, 1);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      reStart() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将已选择调查恢复?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
            return updataStatusByIds(this.ids, 0);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (type == "add"){
          for(let key in this.form){
            this.form[key] = null;
          }
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss">
// .el-dialog {
//     margin-bottom: 5vh;
// }
.el-checkbox {
  margin-right: 0;
  display: block; 
  margin-top: 10px;
}
.el-checkbox__label{
    width: 90%;
    font-size: 24px;
    // float: inline-end;
}
// .el-checkbox__inner{
//     width: 24px;
//     height: 24px;
// }
</style>
